#!/bin/bash

OUTPUT_DIR="json_output"
RECURSIVE=false

while getopts "R" opt; do
  case $opt in
    R) RECURSIVE=true ;;
  esac
done

mkdir -p "$OUTPUT_DIR"

# -------------------------
# Plugin sets per OS
# -------------------------

WINDOWS_PLUGINS=(
  "pslist:windows.pslist"
  "psscan:windows.psscan"
  "psxview:windows.malware.psxview"
  "dlllist:windows.dlllist"
  "ldrmodules:windows.malware.ldrmodules"
  "handles:windows.handles"
  "malfind:windows.malware.malfind"
  "modules:windows.modules"
  "svcscan:windows.svcscan"
  "callbacks:windows.callbacks"
)

LINUX_PLUGINS=(
  "pslist:linux.pslist"
  "psscan:linux.psscan"
  "lsmod:linux.lsmod"
  "check_modules:linux.check_modules"
  "malfind:linux.malfind"
  "bash:linux.bash"
)

MAC_PLUGINS=(
  "pslist:mac.pslist"
  "lsmod:mac.lsmod"
  "malfind:mac.malfind"
)

# -------------------------
# Find memory dumps
# -------------------------

if $RECURSIVE; then
  MEM_FILES=$(find . -type f -name "*.mem")
else
  MEM_FILES=$(find . -maxdepth 1 -type f -name "*.mem")
fi

# -------------------------
# Process dumps
# -------------------------

for mem in $MEM_FILES; do
  base=$(basename "$mem" .mem)
  parent=$(basename "$(dirname "$mem")")

  echo "[+] Inspecting $mem"

  OS="unknown"
  PLUGINS=()

  # --- Detect OS ---
  if vol -f "$mem" windows.info > /dev/null 2>&1; then
    OS="windows"
    PLUGINS=("${WINDOWS_PLUGINS[@]}")
  elif vol -f "$mem" banner > /dev/null 2>&1; then
    OS="linux"
    PLUGINS=("${LINUX_PLUGINS[@]}")
  elif vol -f "$mem" mac.banner > /dev/null 2>&1; then
    OS="mac"
    PLUGINS=("${MAC_PLUGINS[@]}")
  else
    echo "[!] OS detection failed for $mem — skipping"
    continue
  fi

  echo "    → Detected OS: $OS"

  # --- Create OS folder ---
  mkdir -p "$OUTPUT_DIR/$OS"

  # --- Run plugins ---
  for p in "${PLUGINS[@]}"; do
    folder="${p%%:*}"
    plugin="${p##*:}"

    mkdir -p "$OUTPUT_DIR/$OS/$folder"

    out="$OUTPUT_DIR/$OS/$folder/${parent}_${base}.${folder}.json"

    vol -f "$mem" -r json "$plugin" > "$out" 2>/dev/null
  done

done

echo "[✓] OS-aware batch processing complete"

